<!--
 * @Date: 2024-11-21 15:35:50
 * @Author: LiSong
 * @LastEditors: LiSong
 * @LastEditTime: 2025-02-18 13:32:01
 * @Description: 数据列表
-->
<template>
  <div class="hp-chart-panel">
    <div class="hp-chart-panel-header">
      <div class="header-title">{{ schema.label }}</div>
      <div class="header-tools"></div>
    </div>
    <div class="hp-chart-panel-body">
      <el-table
        style="width: 100%; height: 100%;"
        :data="data"
        :stripe="true"
        v-loading="panelState.loading"
      >
        <el-table-column
          v-for="col in columns"
          :key="col.id"
          :prop="col.field"
          :label="col.title"
          :width="col.width"
          :align="col.align"
        />
      </el-table>
    </div>
  </div>
</template>

<script setup>
import { computed, nextTick, onMounted, reactive, ref, watch } from 'vue'
import { commonProps } from '@hp/panels/cfg.js'

import { isEmpty } from '@hp/utils/data.js';
import { useDbSource } from '@hp/hooks/useDbSource.js'

const emits = defineEmits([ 'mounted' ])
const props = defineProps({
  ...commonProps
})

// 数据集
const data = ref([])
const panelState = reactive({
  loading: false
})
// 列表字段
const columns = computed(() => {
  const { columnList } = props.schema
  const result = []
  columnList.forEach((col) => {
    let nCol = {
      id: col.id,
      field: col.field,
      title: col.title,
      width: col.width,
      align: col.align
    }
    if (!nCol.width) {
      delete nCol.width
    }
    result.push(nCol)
  })
  return result
})
// 数据源相关操作
const dbsourceHook = useDbSource({ ...props })

/**
 * 加载数据
 */
const loadData = async () => {
  data.value = []
  reqLoadData()
}
/**
 * 重新加载数据
 */
const reloadData = async (params) => {
  reqLoadData(params)
}

/**
 * 请求加载数据信息
 * 
 * @param params 参数
 */
const reqLoadData = async (params) => {
  panelState.loading = true
  const res = await dbsourceHook.loadDataSource(props.schema, params)
  data.value = isEmpty(res) ? [] : res
  panelState.loading = false
}

onMounted(() => {
  nextTick(() => { emits('mounted') })
})

watch(
  () => props.schema.dataSource,
  (nv, ov) => {
    loadData()
  },
  { deep: true, immediate: true }
)

defineExpose({
  loadData,
  reloadData
})

</script>

<style lang="scss" scoped>
@use '@hp/panels/chart.scss' as *;
</style>